package uit.nfcmenu.activity;

import java.util.ArrayList;

import uit.nfcmenu.R;
import uit.nfcmenu.db.model.IDataChangeHandler;
import uit.nfcmenu.db.model.ItemModel;
import uit.nfcmenu.lib.widget.VerticalTextView;
import uit.nfcmenu.manager.AssetsManager;
import uit.nfcmenu.manager.ItemManager;
import uit.nfcmenu.manager.WaiterGlobalObject;
import uit.nfcmenu.util.UiUtilities.ICallBack;
import uit.nfcmenu.view.ItemAdapter;
import uit.nfcmenu.view.MenuAdapter;
import uit.nfcmenu.webservice.JSONParser;
import uit.nfcmenu.webservice.MyException;
import uit.nfcmenu.webservice.PreferenceHelper;
import uit.nfcmenu.webservice.WSMapping;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.GridView;

public class WaiterItemActivity extends BaseActivity 
		implements OnClickListener, IDataChangeHandler, ICallBack {
	public static String tag = WaiterItemActivity.class.getSimpleName();

	
	// hard 8 // TODO dynamic menu-items numbers in vertical-scroll
//	private ImageView[] ivItems;
//	private Button[] ivItemsListening;
//	private TextView[] mItemNames;
	
//	private TextView txtTile;
//	private Button btnRefresh;
	
	private int position;
	private int mainId;
	private String mainName;
	private ArrayList<ItemModel> mModels;
	
	GridView mItemGrid;
	ItemAdapter adapter;
	VerticalTextView txtTile;
	Button btnTile;
	
	boolean isRunOnFirstTime;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_item);
		
		initView();
		initData();
		initListener();

		isRunOnFirstTime = true;
	}
	
	@Override
	protected Context getActivityContext() {
		return this;
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (isRunOnFirstTime) {
			isRunOnFirstTime = false;
			setProgressBarShowable(true);
			startLoadData(SHOW_MESSAGE_ON_DIALOG);
		}
		if (isDataChangedOnView) {
			Log.e(tag, "isDataChangedOnView=true, reload and view ITEMS from db");
			isDataChangedOnView = false;
			setProgressBarShowable(true);
			mModels = getItemsByMenu();
			updateInView(mModels);
		}
		setProgressBarShowable(false);
	}

	private void startLoadData(int status) {
		boolean result = doIfMeetNetworkOrShowFailStatus(mContext, status, 
				new Runnable() { @Override public void run() {
					new WaiterItemLoader().execute();
				}});
		// if data can not loaded
		if (!result) {
			// load and view from db
			Log.e(tag, "offline, load and view MENUS from db");
			mModels = getItemsByMenu();
			updateInView(mModels);
		}
	}

	@Override
	public void notifyDataChanged() {
		Log.i(tag, "notifyDataChanged() " 
				+"WSMapping.isItemsChanged="+WSMapping.isItemsChanged
				+"isDataChangedOnView="+isDataChangedOnView);
		if (WSMapping.isItemsChanged) {
			doIfMeetNetworkOrShowFailStatus(mContext, SHOW_NOTHING,
					new Runnable() { @Override public void run() {
						new RunLoader(new WaiterItemLoader()).run();	
			}});
		}
	}
	
	@Override
	public Context getContext() {
		return getBaseContext();
	}

	@Override
	protected void initView() {
		super.initView();
		AssetsManager.setCommonAppFont(mContext, R.id.tv_title);
		
		mItemGrid = (GridView) findViewById(R.id.grid);
		btnTile = (Button) findViewById(R.id.btnTitle);
		txtTile = (VerticalTextView)findViewById(R.id.activity_item_tv_menu_test);
	}

	protected void initData() {
		// get data for views
		Bundle bundle = getIntent().getExtras();
		position = bundle.getInt("position");
		mainId = bundle.getInt("mainId");
		mainName = getIntent().getExtras().getString("mainName");
		
		String language = PreferenceHelper.loadLanguage(mContext);
		txtTile.setText(JSONParser.getStringByLanguage(mainName, language));
		txtTile.setSelected(MenuAdapter.isSelectedView(position));
	}

	protected void initListener() {		
		btnTile.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	protected void changeLanguage(String language) { }

	@Override
	public void callBack(int id) {
		launchDetailActivity(id);
	}
	
	public void onClick(View v) {
//		switch (v.getId()) {
//		case R.id.btnRefresh:
//			doIfMeetNetworkOrShowFailStatus(mContext, SHOW_MESSAGE_ON_TOAST,
//					new Runnable() { @Override public void run() {
//						new RunLoader(new WaiterItemLoader()).run();	
//			}});
//			break;
//		}
	}

	private void launchDetailActivity(int index) {
		Intent intent = new Intent(this, WaiterDetailActivity.class);
		Bundle bundle = new Bundle();
		bundle.putInt("itemIdex", index);
		intent.putExtras(bundle);
		startActivity(intent);
	}
	
	@Override
	protected void updateInView(Object... o) {
		ArrayList<ItemModel> models = (ArrayList<ItemModel>) o[0];
		Log.w(tag, "updateList():"+models.size());
		
		WaiterGlobalObject.arrItems = models;
		if (adapter == null) {
			adapter = new ItemAdapter(mContext, models, this); 
			mItemGrid.setAdapter(adapter);
		} else {
			adapter.updateModels(models);
			adapter.notifyDataSetChanged();
		}
	}
	
	private ArrayList<ItemModel> getItemsByMenu() {
		return ItemManager.getInstance(mContext).getItemsByMenu(mainId);
	}
	
	private class WaiterItemLoader extends BaseLoader {
		
		@Override
		protected Integer doInBackground(Void... params) {
			// get data from db. If empty, request data from server
			ArrayList<ItemModel> models = getItems();
			Log.i(tag, "loaded items: "+models.toString());
			if (models == null || models.size() == 0) {
				try {
					ItemManager.getInstance(mContext).updateItems();
				} catch (MyException e) {
					Log.e(tag, "Loader catch MyException ", e);
				}
			}
			mModels = getItemsByMenu();
			
			return super.doInBackground(params);
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			updateInView(mModels);
		}
	}
}
